package com.yuexiao.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yuexiao.entity.ResultInfo;
import com.yuexiao.pojo.Category;
import com.yuexiao.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName:CategoryController
 * @Auther: YUEXIAO
 * @Description: 类别操作控制器
 * @Date: 2022/8/11 18:47
 * @Version: v1.0
 */
@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {

    @Reference
    private CategoryService categoryService;

    /**
     * 分页查询类别列表
     * @param page int 当前页
     * @param pageSize int 每页显示条数
     * @return ResultInfo 返回结果对象
     */
    @GetMapping("/page")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
    public ResultInfo page(int page,int pageSize){
        return ResultInfo.success(categoryService.getCategoryByPage(page,pageSize));
    }


    /**
     * 新增分类
     * @param category Category 类目对象
     * @return ResultInfo 返回结果对象
     */
    @PostMapping("/save")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
    public ResultInfo save(@RequestBody Category category){
        log.info(category.toString());
        boolean result = categoryService.insertCategory(category);
        if (result){
            return ResultInfo.success(null);
        }
        return ResultInfo.error("分类添加失败");
    }

    /**
     * 根据id删除分类
     * @param ids Long 类目主键id
     * @return ResultInfo 返回结果对象
     */
    @DeleteMapping("/deleCategory")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
    public ResultInfo deleCategory(Long ids){
        boolean result = categoryService.deleteCategory(ids);
        if(result){
            return ResultInfo.success(null);
        }
        return ResultInfo.error("删除失败");
    }

    /**
     * 修改类目信息
     * @param category Category 类目对象
     * @return ResultInfo 返回结果对象
     */
    @PutMapping("/editCategory")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
    public ResultInfo editCategory(@RequestBody Category category){
        log.info("修改类目信息:{}",category);
        boolean result = categoryService.updateCategory(category);
        if(result){
            return ResultInfo.success(null);
        }
        return ResultInfo.error("修改失败");
    }

    /**
     * 根据类目类型查询分类列表
     * @param type int 类型id
     * @return ResultInfo 返回结果对象
     */
    @GetMapping("/getCategoryListByType")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
    public ResultInfo getCategoryListByType(int type){
        return ResultInfo.success(categoryService.getCategoryListByType(type));
    }


}
